package com.sign2024.sign2024project.projecttask.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sign2024.sign2024core.common.CommonResult;
import com.sign2024.sign2024core.common.annotation.Log;
import com.sign2024.sign2024core.common.constants.CommonConstants;
import com.sign2024.sign2024core.common.exeception.CommonException;
import com.sign2024.sign2024core.entry.projecttask.FormulaDefault;
import com.sign2024.sign2024core.entry.projecttask.ProjectTask;
import com.sign2024.sign2024project.projecttask.param.ProjectTaskParam;
import com.sign2024.sign2024project.projecttask.service.ProjectTaskService;
import com.sign2024.sign2024project.projecttask.vo.ProjectTaskListVo;
import com.sign2024.sign2024project.projecttask.vo.ProjectTaskVo;
import com.sign2024.sign2024project.projecttask.vo.RollbackVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 工程任务 控制层
 *
 * @author yujie
 * @data 2024/7/31 15:34
 */
//@Api(tags = "工程任务")
@Api(tags = "任务")
@RestController
@RequestMapping("/api/projectTask")
public class ProjectTaskController {

    //    @Resource
    @Autowired
    private ProjectTaskService projectTaskService;

    @Log(title = "任务", businessType = "添加")
    @ApiOperation(value = "添加工程任务", notes = "添加工程任务")
    @PostMapping("/add")
    public CommonResult<ProjectTaskVo> add(@RequestParam @ApiParam("任务标识,0工程服务,1基建,2物资类") Integer taskState) {
        ProjectTaskVo task = projectTaskService.createTask(taskState);
        return CommonResult.success(task);
    }

    @Log(title = "任务", businessType = "查询")
    @ApiOperation(value = "查询任务详细信息", notes = "查询任务详细信息")
    @PostMapping("/selectByid")
    public CommonResult<ProjectTask> selectByid(Integer id) {
        ProjectTask projectTask = projectTaskService.selectProjectTaskData(id);
        return CommonResult.success(projectTask);
    }

    @Log(title = "任务", businessType = "更新")
    @ApiOperation(value = "更新工程任务", notes = "更新工程任务")
    @PostMapping("/update")
    public CommonResult<ProjectTask> update(ProjectTask projectTask) {
        return CommonResult.success(projectTaskService.updateTask(projectTask));
    }

    @Log(title = "任务", businessType = "查询")
    @ApiOperation(value = "分页展示工程任务", notes = "分页展示工程任务")
    @GetMapping("/page")
    public CommonResult<ProjectTaskListVo> page(ProjectTaskParam param) {
        Page<ProjectTaskListVo> list = projectTaskService.pageProjectTask(param);
        return CommonResult.success(list);
    }

    @Log(title = "任务", businessType = "删除")
    @ApiOperation(value = "删除工程任务", notes = "删除工程任务")
    @PostMapping("/delete")
    public CommonResult delete(Integer id) {
        projectTaskService.delFlagTask(id);
        return CommonResult.success();
    }

    @Log(title = "任务", businessType = "更新")
//    @ApiOperation(value = "更新默认公式", notes = "更新默认公式")
    @PostMapping("/saveDefault")
    public CommonResult saveDefault(FormulaDefault formulaDefault) {
        projectTaskService.updateDefault(formulaDefault);
        return CommonResult.success();
    }

    @Log(title = "任务", businessType = "查询")
//    @ApiOperation(value = "默认公式信息", notes = "默认公式信息")
    @GetMapping("/defaultOne")
    public CommonResult<FormulaDefault> defaultOne() {
        FormulaDefault formulaDefault = projectTaskService.selectDefaultOne();
        return CommonResult.success(formulaDefault);
    }

    @Log(title = "任务", businessType = "更新")
//    @ApiOperation(value = "公式回退到默认", notes = "公式回退到默认")
    @Transactional
    @PostMapping("/returnDefault")
    public CommonResult<FormulaDefault> returnDefault() {
        FormulaDefault formulaDefault = projectTaskService.returnDefault();
        if (formulaDefault == null) {
            throw new CommonException(CommonConstants.ERROR, "回退默认数据出错");
        }
        return CommonResult.success(formulaDefault);
    }


    @Log(title = "工程服务", businessType = "导出")
    @PostMapping("/template")
    @ApiOperation(value = "工程服务excel模版", notes = "工程服务excel模版")
    public ResponseEntity<Resource> testExport(HttpServletResponse response
            , @RequestParam @ApiParam("模版标识,1专家余量表,2计划清单,3本批需求一览表,4获取记录汇总,5物料与专业对应关系")
                                                       Integer templateFlag) {
        try {
            String file;
            switch (templateFlag) {
                case 1:
                    file = "专家余量模板.xls";
                    break;
                case 2:
                    file = "工程服务计划清单模板.xlsx";
                    break;
                case 3:
                    file = "工程服务本批需求一览表模板.xlsx";
                    break;
                case 4:
                    file = "工程服务获取记录汇总模板.xlsx";
                    break;
                case 5:
                    file = "工程服务物料与专业对应关系模板.xlsx";
                    break;
                default:
                    throw new CommonException(CommonConstants.ERROR, "模版标识不正确");
            }

//                Resource resource = new ClassPathResource("static/专家余量模板.xls");
            org.springframework.core.io.Resource resource = new ClassPathResource("static/" + file);
            InputStream inputStream = resource.getInputStream();

            String without = getFilWithout(file);

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(without, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            return new ResponseEntity<>(resource, HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @Log(title = "物资", businessType = "导出")
    @PostMapping("/wzplate")
    @ApiOperation(value = "物资excel模版", notes = "物资excel模版")
    public ResponseEntity<Resource> wzplate(HttpServletResponse response
            , @RequestParam @ApiParam("模版标识,1专家余量表,2计划清单,3获取记录汇总,4资质业绩条件,5ecp2.0专业,6专家专业和标段对应关系")
                                                    Integer templateFlag) {
        try {

            String file;
            switch (templateFlag) {
                case 1:
                    file = "专家余量模板.xls";
                    break;
                case 2:
                    file = "物资计划清单模版.xlsx";
                    break;
                case 3:
                    file = "物资获取记录汇总模版.xlsx";
                    break;
                case 4:
                    file = "物资资质业绩条件模版.xlsx";
                    break;
                case 5:
                    file = "物资ecp2.0专业模版.xlsx";
                    break;
                case 6:
                    file = "物资专家专业和标段对应关系模版.xlsx";
                    break;
                default:
                    throw new CommonException(CommonConstants.ERROR, "模版标识不正确");
            }

            org.springframework.core.io.Resource resource = new ClassPathResource("static/" + file);
            InputStream inputStream = resource.getInputStream();

            String without = getFilWithout(file);

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(without, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            return new ResponseEntity<>(resource, HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Log(title = "基建", businessType = "导出")
    @PostMapping("/jjtmpe")
    @ApiOperation(value = "基建excel模版", notes = "基建excel模版")
    public ResponseEntity<Resource> jjtmpe(HttpServletResponse response
            , @RequestParam @ApiParam("模版标识,1专家余量表,2计划清单,3获取记录汇总,4专业汇总")
                                                   Integer templateFlag) {
        try {

            String file;
            switch (templateFlag) {
                case 1:
                    file = "专家余量模板.xls";
                    break;
                case 2:
                    file = "基建计划清单模版.et";
                    break;
                case 3:
                    file = "基建获取记录模版.xlsx";
                    break;
                case 4:
                    file = "基建专业汇总模版.xlsx";
                    break;
                default:
                    throw new CommonException(CommonConstants.ERROR, "模版标识不正确");
            }

            org.springframework.core.io.Resource resource = new ClassPathResource("static/" + file);
            InputStream inputStream = resource.getInputStream();

            String without = getFilWithout(file);

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(without, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            return new ResponseEntity<>(resource, HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取文件名不包括扩展名的方法
     *
     * @param fullFileName 包含扩展名的文件名
     * @return 文件名不包括扩展名的部分
     */
    public static String getFilWithout(String fullFileName) {
        int dotIndex = fullFileName.lastIndexOf('.');
        if (dotIndex == -1) {
            // 如果没找到点，则返回整个文件名
            return fullFileName;
        }
        return fullFileName.substring(0, dotIndex);
    }


    @Log(title = "任务", businessType = "查询")
    @ApiOperation(value = "查询回退历史", notes = "查询回退历史")
    @PostMapping("/selectRollback")
    public CommonResult<RollbackVo> selectRollback(@RequestParam @ApiParam("任务标识,0工程服务,1基建,2物资类") Integer taskState) {
        List<RollbackVo> rollbackVos = projectTaskService.selectRollbackByTaskState(taskState);
        return CommonResult.success(rollbackVos);
    }
}
